<?php

namespace App\Http\Middleware;

use App\Models\Eloquent\AccessLog;
use Closure;
use Illuminate\Support\Facades\DB;

class AfterMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $params = $request->all();
        $data = [
            'method' => $request->method(),
            'route' => $request->getPathInfo(),
            'client_ip' => $request->ip(),
            'params' => $params ? json_encode($params) : '',
            'user_agent' => $request->userAgent(),
            'time' => round(microtime(true) - START, 3)
        ];

        $authToken = $request->bearerToken();
        if ($authToken) {
            $object = \Tymon\JWTAuth\Facades\JWTAuth::setToken($authToken)->getPayload()->get('sub');
            $authInfo = object_to_array($object);
            if (isset($authInfo['enterprise_id'])) {
                $data['enterprise_id'] = $authInfo['enterprise_id'];
            }
        }

        DB::beginTransaction();
        try {
            AccessLog::query()->create($data);
            DB::commit();
        } catch (\Exception $e){
            DB::rollback();
        }

        return $response;
    }
}
